package com.xsmart.common.handle;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xsmart.common.constant.ResultConstant;
import com.xsmart.common.entity.ApiInfo;
import com.xsmart.common.entity.EcomException;
import com.xsmart.common.entity.RequestBean;
import com.xsmart.common.entity.ResponseBean;
import com.xsmart.common.services.GetApiInfoService;
import com.xsmart.common.services.LoginTokenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * api接口统一初始化
 *
 * @author guojd
 */
@ControllerAdvice(value = "com.xsmart")
public class ControllerAdviceHandler {
    @Autowired
    private GetApiInfoService getApiInfoService;
    @Autowired
    private LoginTokenService loginTokenService;

    private Logger logger = LoggerFactory.getLogger(ControllerAdviceHandler.class);

    @ModelAttribute
    public RequestBean initController(HttpEntity<String> httpEntity, HttpServletRequest request, HttpServletResponse response) throws EcomException {
        RequestBean paramBean = null;
        //获取参数
        String data = httpEntity.getBody();
        MediaType mediaType = httpEntity.getHeaders().getContentType();
        if (mediaType.includes(MediaType.APPLICATION_JSON)) {
            ObjectMapper objectMapper = new ObjectMapper();
            logger.debug("request task:" + request.getRequestURI() + " data:" + data);
            try {
                paramBean = data != null ? objectMapper.readValue(data, RequestBean.class) : null;
            } catch (IOException e) {
                throw new EcomException(ResultConstant.ERROR, "参数格式错误", e);
            }
            //判断参数是否为空
            if (paramBean == null) {
                throw new EcomException(ResultConstant.ERROR, "参数错误", new Throwable());
            }
//            ApiInfo apiInfo = getApiInfoService.getApiInfo(request.getRequestURI());
//            if (apiInfo.isLogin() && !loginTokenService.checkUserLoginByToken(paramBean.getToken())) {
//                throw new EcomException(ResultConstant.LOGIN_TIME_OUT, "未登录或登录超时", new Throwable());
//            }
        } else {
            paramBean = new RequestBean();
        }
        if (paramBean.getHttpEntity() == null) {
            paramBean.setHttpEntity(httpEntity);
        }
        return paramBean;
    }

    @ExceptionHandler({Exception.class})
    @ResponseBody
    public ResponseBean validateException(Exception ex) {
        logger.error("请求异常", ex);
        ResponseBean result = new ResponseBean();
        result.setResult(ResultConstant.ERROR);
        result.setMessage(ex.getMessage());
        return result;
    }

    @ExceptionHandler({EcomException.class})
    @ResponseBody
    public ResponseBean validateException(EcomException ex) {
        logger.debug("请求失败", ex);
        ResponseBean result = new ResponseBean();
        result.setResult(ex.getResult());
        result.setMessage(ex.getMessage());
        return result;
    }
}
